package com.hmall.service;

import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hdmall.business.common.util.JsonUtils;
import com.hdmall.business.common.util.PageUtil;
import com.hdmall.business.common.util.RabbitUtil;
import com.hmall.mapper.MallPushMessageMapper;
import com.hmall.mapper.SendMsgManageMapper;
import com.hmall.model.MallPushMessage;
import com.hmall.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息推送服务
 */
@Service
public class MsgService {
    @Autowired
    private MallPushMessageMapper pushMessageMapper;
    @Autowired
    private SendMsgManageMapper sendMsgManageMapper;

    /**
     * direct 队列 必须传userName
     * userName  如果登录 一个随机数 登录后就是手机号
     *
     * @param userName key--对应userId
     * @param sendType 分类
     * @param body     内容
     * @param title    标题
     * @param value    参数
     * @return
     */
    public ServerResponse pcMsgDirectPush(String userName, String sendType, String body, String title, String value, String isImport) throws IOException {

        Map<String, String> paramMap = new HashMap<String, String>();
        if (sendType == null) {
            ServerResponse.createByStatus(ResponseCode.MSG_SENDTYPE_ISEMPTY.getCode(), ResponseCode.MSG_SENDTYPE_ISEMPTY.getDesc(), null);
        }
        if ("news".equals(sendType)) {
            paramMap.put("newsId", value);
        } else if ("product".equals(sendType)) {
            paramMap.put("productId", value);
        } else if ("cer_status".equals(sendType)) {
            paramMap.put("cer_status", value);
        } else if ("order_status".equals(sendType)) {
            paramMap.put("order_no", value);
        } else if ("login".equals(sendType)) {
            paramMap.put("token", value);
        } else if("activity".equals(sendType)){
            paramMap.put("activity", value);
        } else{
            paramMap.put("logout", value);
        }

        Date date = new Date();
        MallPushMessage pushMessage = new MallPushMessage();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        int noReadCont = pushMessageMapper.selectNoReadContByDirect(userName);
        bodyMap.put("body", body);
        bodyMap.put("noReadCont", noReadCont);
        if (isImport == null) {
            isImport = "0";
        }
        bodyMap.put("isImport", isImport);
        pushMessage.setIsRead(0);//没有点击
        pushMessage.setTitle(title);
        pushMessage.setIsPublic(2);
        pushMessage.setUsername(userName);
        pushMessage.setBody(JsonUtils.objectToJsonStr(bodyMap));
        pushMessage.setCreateTime(date);
        pushMessage.setUpdateTime(date);
        pushMessage.setParams(JsonUtils.objectToJsonStr(paramMap));
        pushMessage.setType(sendType);
        pushMessage.setDeviceType(2);//设备2 PC
        String msg = JsonUtils.objectToJsonStr(pushMessage);
        if (userName != null && !"".equals(userName)) {
            pushMessage.setType(sendType);
            //点对点 队列形式推送 sendType 队列名

            if("logout".equals(sendType)){
              //  List<String> queueList = RabbitUtil.getQueue();
                //int flag = 0;
                //for(String queue : queueList){
                 //   if(flag != 0) break;
                 //   if(queue.contains("stomp-subscription")) {
                        ServerResponse response = RabbitUtil.rabbitPushForDirect("hmall_direct_exchg", userName, msg);
                 //       if(response.getStatus() == 0){
                 //           flag++;
                 //       }
                 //   }
                }else {
                RabbitUtil.rabbitPushForDirect("hmall_direct_exchg", sendType, userName, msg);
            }

            }

        //保存信息记录
        pushMessageMapper.insertPushMsg(pushMessage);
        return ServerResponse.createBySuccess(pushMessage);
    }

    /**
     * 登录 一个随机数 登录后就是手机号
     *
     * @param key--一个随机数
     * @param body       内容
     * @param title      标题
     * @param value      参数
     * @return
     */
    public ServerResponse pcMsgScanDirectPush(String key, String body, String title, String value, String isImport) {

        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("token", value);
        Date date = new Date();
        MallPushMessage pushMessage = new MallPushMessage();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
//        int noReadCont= pushMessageMapper.selectNoReadContByDirect(key);
        bodyMap.put("body", body);
//        bodyMap.put("noReadCont",noReadCont);
        if (isImport == null) {
            isImport = "0";
        }
        bodyMap.put("isImport", isImport);
        pushMessage.setIsRead(0);//没有点击
        pushMessage.setTitle(title);
        pushMessage.setIsPublic(2);
        pushMessage.setUsername(key);
        pushMessage.setBody(JsonUtils.objectToJsonStr(bodyMap));
        pushMessage.setCreateTime(date);
        pushMessage.setUpdateTime(date);
        pushMessage.setParams(JsonUtils.objectToJsonStr(paramMap));
        pushMessage.setDeviceType(2);//设备2 PC
        String msg = JsonUtils.objectToJsonStr(pushMessage);
        if (key != null && !"".equals(key)) {
            pushMessage.setType("login" + key);
            //点对点 队列形式推送 sendType 队列名
            RabbitUtil.rabbitPushForDirect("hmall_direct_exchg", pushMessage.getType(), key, msg);
        }
        //保存信息记录
        pushMessageMapper.insertPushMsg(pushMessage);
        return ServerResponse.createBySuccess(pushMessage);
    }

    /**
     * 删除队列
     *
     * @param queueName
     * @return
     */
    public ServerResponse deleteMsg(String queueName) {
        return RabbitUtil.deleteQueue(queueName);
    }

    /**
     * 广播推送
     *
     * @param sendType 分类
     * @param body     内容
     * @param title    标题
     * @param value    参数
     * @return
     */
    public ServerResponse pcMsgPublicPush(String sendType, String body, String title, String value, String isImport) {

        Map<String, String> paramMap = new HashMap<String, String>();
        if (sendType == null) {
            ServerResponse.createByStatus(ResponseCode.MSG_SENDTYPE_ISEMPTY.getCode(), ResponseCode.MSG_SENDTYPE_ISEMPTY.getDesc(), null);
        }
        if ("news".equals(sendType)) {
            paramMap.put("newsId", value);
        } else if ("product".equals(sendType)) {
            paramMap.put("productId", value);
        } else if ("cer_status".equals(sendType)) {
            paramMap.put("cer_status", value);
        } else if ("order_status".equals(sendType)) {
            paramMap.put("order_no", value);
        } else {
            paramMap.put("activity", value);
        }
        if (isImport == null) {
            isImport = "0";
        }
        Date date = new Date();
        MallPushMessage pushMessage = new MallPushMessage();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        int noReadCont = pushMessageMapper.selectNoReadContByPublic();
        bodyMap.put("body", body);
        bodyMap.put("noReadCont", noReadCont);
        bodyMap.put("isImport", isImport);
        pushMessage.setIsRead(0);//没有点击
        pushMessage.setTitle(title);
        pushMessage.setIsPublic(1);
        pushMessage.setBody(JsonUtils.objectToJsonStr(bodyMap));
        pushMessage.setCreateTime(date);
        pushMessage.setUpdateTime(date);
        pushMessage.setParams(JsonUtils.objectToJsonStr(paramMap));
        pushMessage.setType(sendType);
        pushMessage.setDeviceType(2);//设备2 PC
        String msg = JsonUtils.objectToJsonStr(pushMessage);
        //广播形式推送
        RabbitUtil.rabiitPushForPulic("hmall_public_exchg", "", msg);
        //保存信息记录
        pushMessageMapper.insertPushMsg(pushMessage);
        return ServerResponse.createBySuccess(pushMessage);
    }

    /**
     * 往运营后台广播消息 --广播推送
     *
     * @param sendType 分类
     * @param body     内容
     * @param title    标题
     * @param value    参数
     * @return
     */
    public ServerResponse pcMsgToManagerPush(String sendType, String body, String title, String value, String isImport) {

        Map<String, String> paramMap = new HashMap<String, String>();
        if (sendType == null) {
            ServerResponse.createByStatus(ResponseCode.MSG_SENDTYPE_ISEMPTY.getCode(), ResponseCode.MSG_SENDTYPE_ISEMPTY.getDesc(), null);
        }
        if ("news".equals(sendType)) {
            paramMap.put("newsId", value);
        } else if ("product".equals(sendType)) {
            paramMap.put("productId", value);
        } else if ("cer_status".equals(sendType)) {
            paramMap.put("cer_status", value);
        } else if ("order_status".equals(sendType)) {
            paramMap.put("order_no", value);
        } else {
            paramMap.put("activity", value);
        }

        Date date = new Date();
        MallPushMessage pushMessage = new MallPushMessage();
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        int noReadCont = pushMessageMapper.selectNoReadContByPublic();
        bodyMap.put("body", body);
        bodyMap.put("noReadCont", noReadCont);
        bodyMap.put("isImport", isImport);
        pushMessage.setIsRead(0);//没有点击
        pushMessage.setTitle(title);
        pushMessage.setIsPublic(1);
        pushMessage.setBody(JsonUtils.objectToJsonStr(bodyMap));
        pushMessage.setCreateTime(date);
        pushMessage.setUpdateTime(date);
        pushMessage.setParams(JsonUtils.objectToJsonStr(paramMap));
        pushMessage.setType(sendType);
        pushMessage.setDeviceType(2);//设备2 PC
        String msg = JsonUtils.objectToJsonStr(pushMessage);
        //广播形式推送
        RabbitUtil.rabiitPushForPulic("manager_public_exchg", "", msg);
        //保存信息记录
        pushMessageMapper.insertPushMsg(pushMessage);
        return ServerResponse.createBySuccess(pushMessage);
    }

    public ServerResponse<Map<String, Object>> selectPushMsg(Integer pageNo, Integer pageSize, String username, Integer isPublic) {

        if (pageNo == 0) {
            return ServerResponse.createByStatus(ResponseCode.PAGE_IS_ZERO.getCode(), ResponseCode.PAGE_IS_ZERO.getDesc(), null);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        List<MallPushMessage> list = null;
        PageVo<MallPushMessage> pageVo = null;
        Integer noReadCount = 0;
        if (isPublic == 1) {
            //广播
            int total = pushMessageMapper.selectPublicPushMsgTotal();
            if (total > 0) {
                int pageStart = PageUtil.getPage(pageNo, pageSize);
                list = pushMessageMapper.selectPublicPushMsgPage(pageStart, pageSize);
                noReadCount = pushMessageMapper.selectNoReadContByPublic();
                pageVo = new PageVo<MallPushMessage>(pageNo, pageSize, total, list);
                map.put("noReadCount", noReadCount);
                map.put("pageVo", pageVo);
                return ServerResponse.createBySuccess(map);
            } else {
                return ServerResponse.createByStatus(ResponseCode.MSG_ISEMPTY.getCode(), ResponseCode.MSG_ISEMPTY.getDesc(), null);
            }
        } else {//消息队列
            if (username == null || "".equals(username)) {
                return ServerResponse.createByStatus(ResponseCode.USER_NOT_FOUND.getCode(), ResponseCode.USER_NOT_FOUND.getDesc(), null);
            }
            int total = pushMessageMapper.selectDirectPushMsgTotal(username);
            if (total > 0) {
                int pageStart = PageUtil.getPage(pageNo, pageSize);
                list = pushMessageMapper.selectDirectPushMsgPage(pageStart, pageSize, username);
                noReadCount = pushMessageMapper.selectNoReadContByDirect(username);
                pageVo = new PageVo<MallPushMessage>(pageNo, pageSize, total, list);
                map.put("noReadCount", noReadCount);
                map.put("pageVo", pageVo);
                return ServerResponse.createBySuccess(map);
            } else {
                return ServerResponse.createByStatus(ResponseCode.MSG_ISEMPTY.getCode(), ResponseCode.MSG_ISEMPTY.getDesc(), null);
            }
        }

    }

    public ServerResponse updateIsReadPushMsgById(Integer isRead, Integer messageId) {

        pushMessageMapper.updateIsReadPushMsgById(isRead, messageId);
        return ServerResponse.createBySuccess("更新成功");
    }

    public ServerResponse cancelPushMsgById(Integer enable, Integer messageId) {

        pushMessageMapper.cancelPushMsgById(enable, messageId);
        return ServerResponse.createBySuccess("删除成功");
    }

    public ServerResponse deleteRoutingKey(String exchange, String routingKey) {

        return RabbitUtil.deleteRoutingKey(exchange, routingKey);
    }

    public static void main(String args[]){

        ServerResponse response = RabbitUtil.rabbitPushForDirect("hmall_direct_exchg", "17681874720", "不需要queue");
        return ;
    }
}
